package cn.kailangtu.dataspot.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class MarqueeView extends View {
    private String text = "";
    private Paint paint;
    private float offsetX = 0;
    private final float scrollSpeed = 3f;
    private boolean isRunning = true;

    public MarqueeView(Context context) {
        super(context);
        init();
    }

    public MarqueeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setTextSize(48);
        paint.setColor(Color.BLACK);
    }

    public void setText(String text) {
        this.text = text;
        postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 绘制文本
        canvas.drawText(text, offsetX, getHeight()/2f, paint);

        // 更新偏移量
        offsetX -= scrollSpeed;
        if (offsetX < -paint.measureText(text)) {
            offsetX = getWidth();
        }

        // 循环刷新
        if (isRunning) {
            postInvalidateDelayed(16);
        }
    }

    public void pause() {
        isRunning = false;
    }

    public void resume() {
        isRunning = true;
        invalidate();
    }
}